<template>
<div>
    <el-tabs v-model="activeTab" type="border-card" :before-leave="tabSwitchHandle">
        <el-tab-pane name="todo">
            <template #label>
                <el-space>
                    <vp-label zh="待办工作" en="Todo List"/>
                    <el-tag type="error" round>{{ todoTableData.length }}</el-tag>
                    <SvgIcon name="ele-RefreshRight" v-show="activeTab=='todo'" class="ml5"  @click.stop="loadTodoDataList" />
                </el-space>
            </template>
            <vp-table size="small" v-loading="todoLoading" :data="todoTableData" @sort-change="handleTodoTableSortChange" height='379px' row-key="id">
                <el-table-column  type="index" align="center" label="#">
                </el-table-column>
                <el-table-column prop="DEF.NAME_" sortable="custom" width="150" show-overflow-tooltip>
                    <template #header><vp-label zh="流程名称" en="Process Name"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.processName)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="T.NAME_" sortable="custom" width="120" show-overflow-tooltip>
                    <template #header><vp-label zh="节点名称" en="Node Name"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.name)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="REL.title" sortable="custom" min-width="250" show-overflow-tooltip>
                    <template #header><vp-label zh="任务描述" en="Task Desc"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.title)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="T.CREATE_TIME_"  sortable="custom" show-overflow-tooltip width="135">
                    <template #header><vp-label zh="接收时间" en="Receive Time"/></template>
                    <template #default="{row}">
                        {{row.receiveTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="T.PRIORITY_" sortable="custom" width="125">
                    <template #header><vp-label zh="优先级" en="Priority"/></template>
                    <template #default="{row}">
                        <el-tag v-if="row.priority===10" type="danger">立即 Immediate</el-tag>
                        <el-tag v-else-if="row.priority===20" type="warning">紧急 Urgent</el-tag>
                        <el-tag v-else-if="row.priority===30" type="default">急 High</el-tag>
                        <el-tag v-else-if="row.priority===40" type="info">一般 Normal</el-tag>
                        <el-tag v-else type="info">低 Low</el-tag>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" show-overflow-tooltip width="90">
                    <template #header><vp-label-operations/></template>
                    <template #default="scope">
                        <el-space>
                            <vp-btn text @click="handleDo(scope.row)"><vp-label zh="办理" en="Do"/></vp-btn>
                            <vp-btn-view v-if="scope.row.businessView" text @click="handleTaskView(scope.row)" />
                        </el-space>
                    </template>
                </el-table-column>
            </vp-table>
        </el-tab-pane>
        <el-tab-pane name="initiated">
            <template #label>
                <vp-label zh="我发起的流程" en="Initiated By Me"/>
            </template>
            <vp-table size="small" ref="tableRef1" v-loading="loading1" :data="tableData1" @sort-change="handleSortChange1" height="350px" row-key="id">
                <el-table-column  type="index" align="center" label="#">
                </el-table-column>
                <el-table-column prop="DEF.NAME_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="流程名称" en="Process Name"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.processName)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="REL.title" sortable="custom" min-width="200" show-overflow-tooltip >
                    <template #header><vp-label zh="任务描述" en="Task Desc"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.title)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="T.START_TIME_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="开启时间" en="Start Time"/></template>
                    <template #default="{row}">
                        {{row.receiveTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="T.STATE_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="流程状态" en="Process State"/></template>
                    <template #default="{row}">
                        {{row.processInsState == 'ACTIVE'?row.name:row.processInsState}}
                    </template>
                </el-table-column>
                <el-table-column fixed="right"  width="90">
                    <template #header><vp-label-operations/></template>
                    <template #default="scope">
                        <vp-btn-view v-if="scope.row.businessView" text @click="handleTaskView(scope.row)" />
                    </template>
                </el-table-column>
            </vp-table>
            <el-pagination background class="mt5" small
                layout="prev, pager, next, sizes, total" 
                @size-change="page1.pageNum = 1"
                :total="page1.total"
                v-model:currentPage="page1.pageNum"
                v-model:pageSize="page1.pageSize"
                :hide-on-single-page="false"
            >
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane name="done">
            <template #label>
                <vp-label zh="已办工作" en="Done List"/>
            </template>
            <vp-table size="small" ref="tableRef2" v-loading="loading2" :data="tableData2" @sort-change="handleSortChange2" height="350px" :row-key="(row: any) => {return row.id + '_' + row.actId}">
                <el-table-column  type="index" align="center" label="#">
                </el-table-column>
                <el-table-column prop="DEF.NAME_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="流程名称" en="Process Name"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.processName)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="REL.title" sortable="custom" min-width="200" show-overflow-tooltip >
                    <template #header><vp-label zh="任务描述" en="Task Desc"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.title)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="T.START_TIME_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="开启时间" en="Start Time"/></template>
                    <template #default="{row}">
                        {{row.receiveTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="AHT.NAME_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="处理节点" en="Process Node"/></template>
                    <template #default="{row}">
                        {{row.actName}}
                    </template>
                </el-table-column>
                <el-table-column prop="AHT.END_TIME" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="处理时间" en="Process Time"/></template>
                    <template #default="{row}">
                        {{row.endTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="T.STATE_" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="流程状态" en="Process State"/></template>
                    <template #default="{row}">
                        {{row.processInsState == 'ACTIVE'?row.name:row.processInsState}}
                    </template>
                </el-table-column>
                <el-table-column fixed="right"  width="90">
                    <template #header><vp-label-operations/></template>
                    <template #default="scope">
                        <el-space>
                            <vp-btn-back v-if="scope.row.retrievable" text @click="handleBack(scope.row)" />
                            <vp-btn-view v-if="scope.row.businessView" text @click="handleTaskView(scope.row)" />
                        </el-space>
                    </template>
                </el-table-column>
            </vp-table>
            <el-pagination background class="mt5" small
                layout="prev, pager, next, sizes, total" 
                @size-change="page2.pageNum = 1"
                :total="page2.total"
                v-model:currentPage="page2.pageNum"
                v-model:pageSize="page2.pageSize"
                :hide-on-single-page="false"
            >
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane name="draft">
            <template #label>
                <vp-label zh="草稿箱" en="Draft Box"/>
            </template>
            <vp-table size="small" v-loading="loading3" :data="tableData3" @sort-change="handleSortChange3" height="350px" row-key="id">
                <el-table-column  type="index" align="center" label="#">
                </el-table-column>
                <el-table-column prop="ywlx" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="业务类型" en="Business Type"/></template>
                    <template #default="{row}">
                        <span>{{ draftObj(row.ywlx).name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="bt" sortable="custom" min-width="200" show-overflow-tooltip >
                    <template #header><vp-label zh="标题" en="Title"/></template>
                    <template #default="{row}">
                        <span v-html="markTextColor(searchForm.keyword, row.bt)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="whsj" sortable="custom" show-overflow-tooltip width="150">
                    <template #header><vp-label zh="维护时间" en="Edit Time"/></template>
                </el-table-column>
                <el-table-column fixed="right"  width="90">
                    <template #header><vp-label-operations/></template>
                    <template #default="scope">
                        <el-space>
                            <vp-btn-edit text @click="handleEdit(scope.row)" />
                            <vp-btn-del text @click="handleDelete(scope.row)"/>
                        </el-space>
                    </template>
                </el-table-column>
            </vp-table>
            <el-pagination background class="mt5" small
                layout="prev, pager, next, sizes, total" 
                @size-change="page3.pageNum = 1"
                :total="page3.total"
                v-model:currentPage="page3.pageNum"
                v-model:pageSize="page3.pageSize"
                :hide-on-single-page="false"
            >
            </el-pagination>
        </el-tab-pane>
    </el-tabs>
    <div class="searchEle" v-if="tabName != 'myRecord'">
        <el-input v-model="searchForm.keyword" clearable v-trim style="width: 500px;" :placeholder="activeTab !== 'draft' ? '流程名称 Process Name/节点名称 Node Name/任务描述 Task Desc' : '标题 Title'">
            <template #append>
                <el-button icon="ele-Search" @click="handleSearch"></el-button>
            </template>
        </el-input>
    </div>
</div>
</template>
<script setup lang="ts" name='userTaskCard'>
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, getCurrentInstance, onBeforeMount, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { defaultPage, Page } from '../../common/model';
import request from '/@/utils/request';
import commonFunction from '/@/utils/commonFunction';
import mittBus from '/@/utils/mitt';
import VpMessageBox from '/@/components/vp/VpMessageBox';

    const searchForm = ref({
		keyword: "",
	});
    const todoLoading = ref(false);
    const todoTableData = ref([]);
    const timer = ref();

    const page = ref<Page>({
        ...defaultPage
    })

    const { proxy } = getCurrentInstance() as any;

    
    onBeforeMount(()=>{
        mittBus.on('todoFinish', () => {
            onTodoFinish();
        });
    })

    const onTodoFinish = ()=>{
        loadTodoDataList();
    }

    onUnmounted(() => {
        // 取消非本页面调用监听
        mittBus.off('todoFinish');
    });


    onMounted(()=>{
        loadTodoDataList();
        loadDraftTypes();
        timer.value = window.setInterval(timerFunc, 1000*60*5);
    })

    const timerFunc = ()=>{
        if(!todoLoading.value){
            loadTodoDataList();
        }
    }
    onDeactivated(()=>{
        window.clearInterval(timer.value)
    })

    const loadTodoDataList = () => {
        if(todoLoading.value){
            return;
        }
        todoLoading.value = true
        request.get('/workflow/todo/list', {
            params: {
                ...searchForm.value,
                ...page.value,
            },
		}).then(res => {
            todoTableData.value = res?.data || []
        }).finally(()=>{
            todoLoading.value = false
        })
    }

    const handleTodoTableSortChange = (column: any)=>{
        page.value.sortColumn = column.prop;
        page.value.sortOrder = column.order == 'descending' ? 'desc': 'asc'
        loadTodoDataList()
    }

    const router = useRouter();
    const handleDo = (row: any)=>{
        console.log(row,"row",row.id)
        if(row.view){
            router.push({
                name: row.view,
                params: {
                    processInsId: row.processInsId,
                    taskId: row.id,
                    businessId: row.businessId,
                },
            })
        }else{
            ElMessage.error("未定义的表单，请联系管理员");
        }
    }

    const handleTaskView = (row: any)=>{
        console.log(row,"row")
        if(row.businessView){
            router.push({
                name: row.businessView,
                params: {
                    id:row.businessId
                },
            })
        }else{
            ElMessage.error("未定义的表单，请联系管理员");
        }
    }

    const {markTextColor} = commonFunction();

    const page1 = ref<Page>({
        ...defaultPage
    })

    const page2 = ref<Page>({
        ...defaultPage
    })

    const page3 = ref<Page>({
        ...defaultPage
    })

    const loading1 = ref(false);
    const loading2 = ref(false);
    const loading3 = ref(false);

    const tableData1 = ref([]);
    const tableData2 = ref([]);
    const tableData3 = ref([]);

    const loadDataList1 = () => {
        loading1.value = true
        request.get('/workflow/initiated/list', {
            params: {
                ...searchForm.value,
                ...page1.value,
            }
        }).then(res => {
            tableData1.value = res?.data?.list || []
            page1.value.total = res?.data?.total || 0
            page1.value.pageNum = res?.data?.pageNum || 1
        }).finally(()=>{
            loading1.value = false
        })
    }

    const loadDataList2 = () => {
        loading2.value = true
        request.get('/workflow/done/list', {
            params: {
                ...searchForm.value,
                ...page2.value,
            }
        }).then(res => {
            tableData2.value = res?.data?.list || []
            page2.value.total = res?.data?.total || 0
            page2.value.pageNum = res?.data?.pageNum || 1
        }).finally(()=>{
            loading2.value = false
        })
    }

    const loadDataList3 = () => {
        loading3.value = true
        request.get('/draft/list', {
            params: {
                ...searchForm.value,
                ...page3.value,
            }
        }).then(res => {
            tableData3.value = res?.data?.list || []
            page3.value.total = res?.data?.total || 0
            page3.value.pageNum = res?.data?.pageNum || 1
        }).finally(()=>{
            loading3.value = false
        })
    }

    const draftTypes = ref([]);
    const loadDraftTypes = () => {
        request.get('/draft/types').then(res => {
            draftTypes.value = res?.data || [];
        })
    }

    const draftObj = computed(() => {
        return (code: string) => {
            return (draftTypes.value || []).find((type: any) => { return type.code === code}) || {} as any;
        }
    });

    const handleEdit = (row: any)=>{
        console.log(row,"row修改")
        const draft = draftObj.value(row.ywlx);
        if(draft && draft.editView){
            router.push({
                name: draft.editView,
                params: {
                    id: row.ywid
                },
            })
        }else{
            ElMessage.error("未定义的表单，请联系管理员");
        }
    }

    // 删除
    const handleDelete = (row: any)=>{
        const draft = draftObj.value(row.ywlx);
        if(draft && draft.deleteUrl){
            VpMessageBox.confirmDelete().then(()=>{
            request.delete(`/${draft.deleteUrl}/${row.ywid}`).then(res => {
                loadDataList3();
            })
        });
        }else{
            ElMessage.error("未定义的表单，请联系管理员");
        }
    }

    const handleSortChange1 = (column: any)=>{
        page1.value.sortColumn = column.prop;
        page1.value.sortOrder = column.order == 'descending' ? 'desc': 'asc'
        loadDataList1()
    }
    const handleSortChange2 = (column: any)=>{
        page2.value.sortColumn = column.prop;
        page2.value.sortOrder = column.order == 'descending' ? 'desc': 'asc'
        loadDataList2()
    }
    const handleSortChange3 = (column: any)=>{
        page3.value.sortColumn = column.prop;
        page3.value.sortOrder = column.order == 'descending' ? 'desc': 'asc'
        loadDataList3()
    }

    watch(()=>[page1.value.pageNum, page1.value.pageSize], ()=>{
        loadDataList1()
    })
    watch(()=>[page2.value.pageNum, page2.value.pageSize], ()=>{
        loadDataList2()
    })
    watch(()=>[page3.value.pageNum, page3.value.pageSize], ()=>{
        loadDataList3()
    })

    const activeTab = ref("todo");

    let tabName = 'todo';
    /**
     * 切换tab前的事件
     */
    const tabSwitchHandle = (activeName, oldActiveName)=>{
        if(activeName === "todo"){
            loadTodoDataList();
        }else if(activeName === "initiated"){
            loadDataList1();
        }else if(activeName === "done"){
            loadDataList2();
        }else if(activeName === "draft"){
            loadDataList3();
        }
        tabName = activeName;
    }

    /**
     * 查询按钮
     */
    const handleSearch = () => {
        if(activeTab.value === "todo"){
            loadTodoDataList();
        }else if(activeTab.value === "initiated"){
            loadDataList1();
        }else if(activeTab.value === "done"){
            loadDataList2();
        }else if(activeTab.value === "draft"){
            loadDataList3();
        }
    }

    /**
     * 取回任务
     * @param row 
     */
    const handleBack = (row: any) => {
        VpMessageBox.confirm({
			zh: '是否确定取回流程？',
			en: 'Are you sure about the retrieval process?',
		}, {
			zh: '提示',
			en: 'Info',
		}, {
			type: 'warning',
		}).then(()=>{
            loading2.value = true;
            request.post('/workflow/back',{
                processInsId: row.processInsId,
                nextStep: row.taskDefKey,
            }).then(()=>{
                loadDataList2()
                ElMessage.success("操作成功/Success.");
            }).finally(()=>{
                loading2.value = false
            })
        });
    }

</script>
<style scoped lang="scss">
.searchEle {
    position:absolute;
    top: 4px;
    right: 4px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  :deep(.button){
	padding: 0;
    min-height: auto;
  }
}
</style>